package org.zjt.lock;

import java.util.Arrays;
import java.util.Random;

public class BlockQueue2<T> {
    private final int cap ;
    private volatile int size;
    private final Object[] list ;


    public BlockQueue2(int cap) {
        this.cap = cap;
        this.size = 0;
        list = new Object[cap];
    }

    public synchronized void put (T t) throws InterruptedException {
        while (size >= cap){
            this.wait();
        }
        Thread.sleep(Math.abs(new Random().nextInt()) % 100);
        int index = size ;
        list[index] = t;
        size +=1;
        this.notify();
    }

    public synchronized T get () throws InterruptedException {
        while (size < 1){
            this.wait();
        }
        Thread.sleep(Math.abs(new Random().nextInt()) % 100);
        Object obj = list[0];
        for(int i = 1 ;i < size;i++){
            list[i -1]= list[i];
        }
        size -=1;
        this.notify();
        return (T)obj;
    }

    public static void main(String[] args) throws InterruptedException {
        BlockQueue2<Object> queue = new BlockQueue2(10);
        new Thread(() -> {
            Arrays.asList(1,2,3,2,32,3,32,3,"sds",7878).stream().forEach(
                    item -> {
                        try {
                            queue.put(item);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    });
        }).start();

        new Thread(() -> {
            for (;;){
                try {
                    System.out.println(queue.get());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        Thread.sleep(10000000);
    }

}
